#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name：      operate_toml.py
   Remark :         企业级 TOML 操作工具类
-------------------------------------------------
"""

import toml
from pathlib import Path
from typing import Any, Optional, Union
import logging

# 模块公开接口
__all__ = ["TOMLHandler", "toml_handler"]

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(name)s - %(message)s",
)
logger = logging.getLogger("TOMLHandler")


class TOMLHandler:
    """
    企业级 TOML 操作工具类
    提供读取、写入、格式化和验证 TOML 的统一接口。
    """

    @staticmethod
    def read_toml_file(filepath: Union[str, Path]) -> Any:
        """
        读取 TOML 文件并解析为 Python 对象。

        :param filepath: TOML 文件路径
        :return: Python 对象（通常是 dict）
        :raises FileNotFoundError: 文件不存在
        :raises toml.TomlDecodeError: TOML 格式错误
        """
        filepath = Path(filepath)
        logger.info(f"Reading TOML file: {filepath}")
        if not filepath.exists():
            logger.error(f"File not found: {filepath}")
            raise FileNotFoundError(f"File not found: {filepath}")

        try:
            with open(filepath, "r", encoding="utf-8") as file:
                data = toml.load(file)
                logger.debug(f"TOML file loaded successfully: {filepath}")
                return data
        except toml.TomlDecodeError as e:
            logger.error(f"Failed to decode TOML file: {filepath} | Error: {e}")
            raise

    @staticmethod
    def write_toml_file(filepath: Union[str, Path], data: Any) -> None:
        """
        将 Python 对象写入 TOML 文件。

        :param filepath: TOML 文件路径
        :param data: Python 对象（通常是 dict）
        """
        filepath = Path(filepath)
        logger.info(f"Writing TOML to file: {filepath}")
        try:
            with open(filepath, "w", encoding="utf-8") as file:
                toml.dump(data, file)
                logger.debug(f"TOML file written successfully: {filepath}")
        except Exception as e:
            logger.error(f"Failed to write TOML to file: {filepath} | Error: {e}")
            raise

    @staticmethod
    def parse_toml_string(toml_string: str) -> Any:
        """
        将 TOML 字符串解析为 Python 对象。

        :param toml_string: TOML 格式的字符串
        :return: Python 对象
        :raises toml.TomlDecodeError: TOML 格式错误
        """
        logger.info("Parsing TOML string")
        try:
            data = toml.loads(toml_string)
            logger.debug("TOML string parsed successfully")
            return data
        except toml.TomlDecodeError as e:
            logger.error(f"Failed to decode TOML string | Error: {e}")
            raise

    @staticmethod
    def serialize_to_toml_string(data: Any) -> str:
        """
        将 Python 对象序列化为 TOML 格式字符串。

        :param data: Python 对象
        :return: TOML 格式的字符串
        """
        logger.info("Serializing Python object to TOML string")
        try:
            toml_string = toml.dumps(data)
            logger.debug("Python object serialized to TOML string successfully")
            return toml_string
        except Exception as e:
            logger.error(f"Failed to serialize object to TOML string | Error: {e}")
            raise

    @staticmethod
    def pretty_print_toml(data: Any) -> None:
        """
        格式化输出 TOML 数据到控制台。

        :param data: Python 对象（通常是 dict）
        """
        logger.info("Pretty printing TOML data")
        try:
            print(toml.dumps(data))
        except Exception as e:
            logger.error(f"Failed to pretty print TOML data | Error: {e}")
            raise


# 全局实例化，便于外部调用
toml_handler = TOMLHandler()

# 示例用法
if __name__ == "__main__":
    # 读取 TOML 文件
    try:
        data = toml_handler.read_toml_file("example.toml")
        toml_handler.pretty_print_toml(data)
    except Exception as e:
        logger.error(e)

    # 写入 TOML 文件
    example_data = {
        "name": "Alice",
        "age": 30,
        "languages": ["English", "Chinese"],
        "details": {"hobby": "reading", "active": True},
    }
    try:
        toml_handler.write_toml_file("output.toml", example_data)
    except Exception as e:
        logger.error(e)

    # TOML 字符串解析
    toml_str = """
    [user]
    name = "Bob"
    age = 25
    """
    try:
        parsed_data = toml_handler.parse_toml_string(toml_str)
        logger.info(parsed_data)
    except Exception as e:
        logger.error(e)

    # 序列化 Python 对象为 TOML 字符串
    try:
        toml_string = toml_handler.serialize_to_toml_string(example_data)
        logger.info(toml_string)
    except Exception as e:
        logger.error(e)

# 全局实例化，便于外部调用
toml_handler = TOMLHandler()

# 示例用法
if __name__ == '__main__':
    # 读取 TOML 文件
    data = toml_handler.read_toml_file("config.toml")
    toml_handler.pretty_print_toml(data)

    # 写入 TOML 文件
    toml_handler.write_toml_file("output.toml", {"key": "value"})

    # 解析 TOML 字符串
    parsed_data = toml_handler.parse_toml_string("[user]\nname = 'Alice'\nage = 30")
    print(parsed_data)

    # 序列化 Python 对象为 TOML 字符串
    toml_string = toml_handler.serialize_to_toml_string({"key": "value"})
    print(toml_string)
